<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.net.*"%>
<%@page import="java.sql.*"%>
<%@page import="org.json.simple.*"%>
<%@page import="java.util.*"%>
<%@page import="connection.DbConnection"%>
<%	
	//Establish database connection, get table data.
		DbConnection conn = new DbConnection();
		
		String qID = request.getParameter("questionid");
		String setState = request.getParameter("setstate");//1 if we want to toggle question state, else 0
		String optionid = request.getParameter("optionid");
		int QuestionID = -1;
		int correct = -1;
		try{
			QuestionID = Integer.parseInt(request.getParameter("questionid"));
		}catch(Exception e){
			System.out.println("Exception! "+Integer.toString(QuestionID));	
		}
		int status = -1;
		System.out.println("qID:"+qID);
		
		//get state
		try{
			String sql = "SELECT status FROM Question WHERE QuestionID="+qID;
			PreparedStatement ps = conn.getConn().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				System.out.println("here2");
				status = rs.getInt(1);
				System.out.println(status);
			}
		}catch(Exception e){
			System.out.println("Error in setQuestionState! [getting status]");
			e.printStackTrace();
		}
		
		
		//toggle state
		if(setState.equals("1")){
			String sql = "UPDATE Question SET status = ";
			
			System.out.println("togglingquestion");
			if(status == 0){
				sql += "1";
			}else{
				sql += "0";
			}
			sql += " WHERE QuestionID = "+QuestionID;
			System.out.println(sql);
			PreparedStatement ps = conn.getConn().prepareStatement(sql);
			try{
				ps.executeQuery();
			}catch(Exception e){
				System.out.println("Error in setQuestionState! [setting status]");
				e.printStackTrace();
			}
		}
		
		try{
			if(status != -1){
				session.setAttribute("setQuestionState3", status);
			}
			JSONObject obj = new JSONObject();
			obj.put("status", status);
			obj.put("optionid", optionid);
			obj.put("correct", correct);
			System.out.println("status:"+status);
			out.print(obj);
			out.flush();
		}catch(Exception e){
			System.out.println("setQuestionState: Problem's here!");
		}
%>